package com.zjtobacco.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zjtobacco.Constants;
import com.zjtobacco.domain.Goods;
import com.zjtobacco.domain.Warehouse;
import com.zjtobacco.service.GoodsService;

@Controller
@RequestMapping("/goods")
public class GoodsController {
	@Autowired
	private GoodsService goodsService;

	@RequestMapping("list")
	public ModelAndView list(Goods goods) {
		List<Goods> goodsList = null;
		ModelAndView modelAndView = new ModelAndView("goods/list");
		try {
			goodsList = goodsService.list(goods);
		} catch (Exception e) {
			e.printStackTrace();
		}

		modelAndView.addObject("goodsList", goodsList);
		return modelAndView;
	}

	@RequestMapping("add")
	public ModelAndView add() {
		List<String> types = new ArrayList<String>();
		types.add(Constants.TYPE_CORE);
		types.add(Constants.TYPE_LINK);
		types.add(Constants.TYPE_NORMAL);
		
		ModelAndView modelAndView = new ModelAndView("goods/edit");
		modelAndView.addObject("types", types);
		
		return modelAndView;
	}

	@RequestMapping("save")
	public String save(Goods goods) {
		try {
			if (goods.getId() == null) {
				goodsService.save(goods);
			} else {
				goodsService.update(goods);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:./list";
	}

	@RequestMapping("update")
	public ModelAndView update(Goods goods) {
		List<String> types = new ArrayList<String>();
		types.add(Constants.TYPE_CORE);
		types.add(Constants.TYPE_LINK);
		types.add(Constants.TYPE_NORMAL);
		
		ModelAndView modelAndView = new ModelAndView("goods/edit");
		try {
			modelAndView.addObject("types", types);
			
			Goods wh = goodsService.get(goods.getId());

			modelAndView.addObject("goods", wh);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return modelAndView;
	}

	@RequestMapping("delete")
	public String delete(Warehouse warehouse) {
		try {
			goodsService.delete(warehouse.getId());

			// modelAndView.addObject("warehouse", wh);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:./list";
	}

}
